//
//  FuelStatTableView.m
//  carcareIOS
//
//  Created by ileo on 16/4/11.
//  Copyright © 2016年 chezheng. All rights reserved.
//

#import "FuelStatView.h"
#import "HorizontalTableView.h"
#import "FuelMonthHCell.h"
#import "UIScrollView+LoadMore.h"
#import "CalendarMgr.h"
#import "AIUserInfo.h"

#define TIMES_MIN 60
#define TIMES_MAX 90
#define COSTS_MIN 60
#define COSTS_MAX 70
#define FUELS_MIN 60
#define FUELS_MAX 90


@interface FuelStatView ()<HorizontalTableViewDataSourse,LoadMoreControllerDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) HorizontalTableView *hTableView;

@property (nonatomic, strong) FuelMgr *fuelMgr;

@property (nonatomic, strong) UILabel *titleL;

@property (nonatomic , strong) UILabel * oilMoneyL;//金额label

@property (nonatomic , strong) UILabel * oilTimesL;//加油次数

@property (nonatomic , strong) UILabel * oilVolumeL;//加油升数

@property (nonatomic, strong) UIView *line;

@property (nonatomic, assign) CGFloat max;
@property (nonatomic, assign) CGFloat min;

@end

@implementation FuelStatView

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [Theme mainColor];
        [self createHeadLabelView];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateFuelMonthInfo) name:FUEL_UPDATE object:nil];
        
    }
    return self;
}
-(void)configMax:(CGFloat)max min:(CGFloat)min{
    self.max = max;
    self.min = min;
}
- (void)createHeadLabelView
{
    UIView * headBackView = [[[UIView viewWithFrame:CGRectMake(0 , 0, __MAIN_WIDTH, 115)] resetBackgroundColor:[UIColor clearColor]] setupOnView:self];
    self.titleL = [Factory labelWithFrame:CGRectMake(12 * __MAIN_RATIO_375, 15, headBackView.width - 12 * __MAIN_RATIO_375 * 2, 20) font:FONT_DEFAULT_Light(14) text:@"本月累计加油:" textColor:COLOR_HEXSTRING(@"#a3e6ff") onView:headBackView textAlignment:NSTextAlignmentLeft];
    CGFloat leftAndRightLabelW = 80;
    CGFloat moneyLW = headBackView.width - leftAndRightLabelW * 2;
    self.oilMoneyL = [Factory labelWithFrame:CGRectMake((headBackView.width - moneyLW) / 2, self.titleL.bottom + 4, moneyLW, 40) font:FONT_DEFAULT_Light(17) text:@"" textColor:[UIColor whiteColor] onView:headBackView textAlignment:NSTextAlignmentCenter];
    self.oilMoneyL.backgroundColor = [UIColor clearColor];

    self.oilTimesL = [Factory labelWithFrame:CGRectMake(0, self.oilMoneyL.bottom + 3, leftAndRightLabelW, 20) font:FONT_DEFAULT_Light(17) text:@"" textColor:[UIColor whiteColor] onView:headBackView textAlignment:NSTextAlignmentCenter];
    self.oilVolumeL = [Factory labelWithFrame:CGRectMake(headBackView.width - leftAndRightLabelW, self.oilTimesL.top, leftAndRightLabelW, self.oilTimesL.height) font:FONT_DEFAULT_Light(17) text:@"" textColor:[UIColor whiteColor] onView:headBackView textAlignment:NSTextAlignmentCenter];

}
-(void)setFrame:(CGRect)frame{
    [super setFrame:frame];
    CGFloat rate = (self.height - self.min) / (self.max - self.min);
    if (rate >= 0) {
        self.titleL.alpha = rate;
        self.oilTimesL.bottom = TIMES_MIN + (TIMES_MAX - TIMES_MIN) * rate;
        self.oilMoneyL.bottom = COSTS_MIN + (COSTS_MAX - COSTS_MIN) * rate;
        self.oilVolumeL.bottom = FUELS_MIN + (FUELS_MAX - FUELS_MIN) * rate;
        self.hTableView.frame = CGRectMake(0, self.height - 188, self.width, 188);
        self.line.top = self.height - 1;
        for (FuelMonthHCell *cell in self.hTableView.visibleCells) {
            cell.barAlpha = rate;
        }
    }
}
- (void)reloadHeadVDataWithMoney:(CGFloat)moneyF withTimes:(NSInteger)times withOilVolume:(CGFloat)oilVolume
{
    NSString * moneyStr = [NSString stringWithFormat:@"%0.02f",moneyF];
    NSArray * moneyStrArr = [moneyStr componentsSeparatedByString:@"."];
    [self.oilMoneyL setAttributedText:[self titleWithNameStr:@"¥ " withUnitStr:moneyStrArr[0] withThreeStr:(moneyStrArr.count > 1 ? [NSString stringWithFormat:@".%@",moneyStrArr[1]] : @"") withUnitFont:FONT_DEFAULT_Light(40) withUnitColor:[UIColor whiteColor]]];
    
    [self.oilTimesL setAttributedText:[self titleWithNameStr:STRING_INT(times) withUnitStr:@"次" withThreeStr:@"" withUnitFont:FONT_DEFAULT_Light(14) withUnitColor:[UIColor whiteColor]]];
    
    [self.oilVolumeL setAttributedText:[self titleWithNameStr:[NSString stringWithFormat:@"%.01f",oilVolume] withUnitStr:@"升" withThreeStr:@"" withUnitFont:FONT_DEFAULT_Light(14) withUnitColor:[UIColor whiteColor]]];
}
-(void)updateFuelMonthInfo{
    
    FuelMonthModel * model = [[FuelMgr sharedInstance]fuelModelWithMonthModel:[FuelMgr sharedInstance].currentMonth];
    if(model.modelDic.count > 0)[self reloadHeadVDataWithMoney:model.totalCost withTimes:model.totalTimes withOilVolume:model.totalFuelL];
    [self.hTableView reloadData];
}
#pragma mark - 生成使用的attribute str
- (NSMutableAttributedString *)titleWithNameStr:(NSString *)nameStr withUnitStr:(NSString *)unitStr withThreeStr:(NSString *)threestr withUnitFont:(UIFont *)font withUnitColor:(UIColor *)color
{
    NSString * str = [NSString stringWithFormat:@"%@%@%@",nameStr, unitStr,threestr];
    NSMutableAttributedString * attributeStr = [[NSMutableAttributedString alloc]initWithString:str];
    if([unitStr length] > 0)
    {
        NSRange range = NSMakeRange([str length] - [unitStr length] - [threestr length], [unitStr length]);
        [attributeStr addAttribute:NSFontAttributeName value:font range:range];
        if(color)[attributeStr addAttribute:NSForegroundColorAttributeName value:color range:range];
    }
    return attributeStr;
}


#pragma mark -
-(void)showMonth:(DateModel *)dateModel{
    NSInteger index = [self.fuelMgr indexWithDateModel:dateModel];
    CGFloat left = (index + 0.5) * [FuelMonthHCell cellWidth] - CGRectGetWidth(self.frame) / 2;
    [self.hTableView setContentOffset:CGPointMake(left, 0) animated:YES];
}

#pragma mark - loadmore

-(void)loadMoreLeftFinish:(void (^)(CGFloat insetWidth))finish withScrollView:(UIScrollView *)scrollView{
    __weak __typeof(self) wself = self;
    [self.fuelMgr addLastMonthCallback:^(BOOL succ) {
        [wself updateFuelMonthInfo];
        finish(succ ? [FuelMonthHCell cellWidth] : 0);
    }];
}

-(void)loadMoreRightFinish:(void (^)())finish withScrollView:(UIScrollView *)scrollView{
    __weak __typeof(self) wself = self;
    [self.fuelMgr addNextMonthCallback:^(BOOL succ) {
        [wself updateFuelMonthInfo];
        finish();
    }];
}

#pragma mark - scroll

-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    CGFloat center = scrollView.contentOffset.x + CGRectGetWidth(scrollView.frame) / 2;
    NSInteger index = center / [FuelMonthHCell cellWidth];
    if (index != [self.fuelMgr indexWithDateModel:self.fuelMgr.currentMonth]) {
        self.fuelMgr.currentMonth = self.fuelMgr.months[index];
        [self updateFuelMonthInfo];
        if(self.scrollChangeMonthReload)self.scrollChangeMonthReload();
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGFloat center = scrollView.contentOffset.x + CGRectGetWidth(scrollView.frame) / 2;
    NSInteger index = center / [FuelMonthHCell cellWidth];
    if (index != [self.fuelMgr indexWithDateModel:self.fuelMgr.currentMonth]) {
        self.fuelMgr.currentMonth = self.fuelMgr.months[index];
        [self updateFuelMonthInfo];
        if(self.scrollChangeMonthReload)self.scrollChangeMonthReload();
    }
}
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    CGFloat center = targetContentOffset->x + CGRectGetWidth(scrollView.frame) / 2;
    NSInteger index = center / [FuelMonthHCell cellWidth];
    targetContentOffset->x = (index + 0.5) * [FuelMonthHCell cellWidth] - CGRectGetWidth(self.frame) / 2;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat center = scrollView.contentOffset.x + CGRectGetWidth(scrollView.frame) / 2;
    for (FuelMonthHCell *cell in self.hTableView.visibleCells) {
        CGFloat sub = [FuelMonthHCell cellWidth]/2 - ABS(cell.centerX - center);
        CGFloat rate = 1;
        if (sub >= 0) rate = ([FuelMonthHCell cellWidth]/2 - sub) / ([FuelMonthHCell cellWidth] / 2);
        cell.barOpacity = rate;
    }
}

#pragma mark - htableView delegate

-(CGFloat)horizontalTableView:(HorizontalTableView *)horizontalTableView widthForRow:(NSInteger)row{
    return [FuelMonthHCell cellWidth];
}

-(HorizontalTableViewCell *)horizontalTableView:(HorizontalTableView *)horizontalTableView cellForRow:(NSInteger)row{
    static NSString *cellID = @"cell";
    FuelMonthHCell *cell = [horizontalTableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[FuelMonthHCell alloc] initWithReuseIdentifier:cellID];
        [cell configHeight:horizontalTableView.height];
    }
    FuelMonthModel *model = [self.fuelMgr fuelModelWithMonthModel:self.fuelMgr.months[row]];
    if (model) {
        CGFloat height = self.fuelMgr.maxFuelCost > 0 ? ((horizontalTableView.height - 23) * (model.totalCost / self.fuelMgr.maxFuelCost)) : 0;
        NSString *date = model.monthModel.month == 1 ?
                        [NSString stringWithFormat:@"%zd年%zd月",model.monthModel.year,model.monthModel.month] :
                        [NSString stringWithFormat:@"%zd月",model.monthModel.month];
        __weak __typeof(self) wself = self;
        BOOL isChoice = model.monthModel == self.fuelMgr.currentMonth;
        [cell setMonth:date height:height isChoice:isChoice click:^{
            if (![CALENDARMGR dateModel:model.monthModel monthIsBeforeThanDateModel:USERINFO.bindingDay] && ![CALENDARMGR dateModel:CALENDARMGR.today monthIsBeforeThanDateModel:model.monthModel]) {
                [wself showMonth:model.monthModel];
            }
        }];
        cell.barOpacity = isChoice ? 0 : 1;
    }
    CGFloat rate = (self.height - self.min) / (self.max - self.min);
    cell.barAlpha = rate;
    return cell;
}

-(NSInteger)numberOfRowsWithHorizontalTableView:(HorizontalTableView *)horizontalTableView{
    return self.fuelMgr.months.count;
}

#pragma mark -
-(HorizontalTableView *)hTableView{
    if (!_hTableView) {
        _hTableView = [[HorizontalTableView alloc] init];
        _hTableView.dataSource = self;
        _hTableView.delegate = self;
        [self addSubview:_hTableView];
        _hTableView.showsHorizontalScrollIndicator = NO;
        _hTableView.bounces = NO;
        [_hTableView setLoadMoreDelegate:self];
        [_hTableView setLoadMoreLeftView:[[LoadMoreView alloc] initWithFrame:CGRectMake(0, 0, 1, _hTableView.height)]];
        [_hTableView setLoadMoreRightView:[[LoadMoreView alloc] initWithFrame:CGRectMake(0, 0, 1, _hTableView.height)]];
        self.line = [[[UIView viewWithFrame:CGRectMake(0,0, __MAIN_WIDTH,0.5)] resetBackgroundColor:[Theme lineColor]] setupOnView:self];
    }
    return _hTableView;
}

-(FuelMgr *)fuelMgr{
    if (!_fuelMgr) {
        _fuelMgr = [FuelMgr sharedInstance];
    }
    return _fuelMgr;
}

@end
